package com.wskj.workbench.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wskj.common.core.mybatisplus.core.ServicePlusImpl;
import com.wskj.common.core.page.PagePlus;
import com.wskj.common.core.page.TableDataInfo;
import com.wskj.common.utils.common.AssertUtils;
import com.wskj.common.utils.common.PageUtils;
import com.wskj.common.utils.common.SecurityUtils;
import com.wskj.workbench.bo.app.AppTbUserReceiveAddBo;
import com.wskj.workbench.bo.app.AppTbUserReceiveEditBo;
import com.wskj.workbench.bo.app.AppTbUserReceiveQueryBo;
import com.wskj.workbench.bo.web.TbUserReceiveAddBo;
import com.wskj.workbench.bo.web.TbUserReceiveEditBo;
import com.wskj.workbench.bo.web.TbUserReceiveQueryBo;
import com.wskj.workbench.domain.TbUserReceive;
import com.wskj.workbench.enums.IfDefaultEnum;
import com.wskj.workbench.mapper.TbUserReceiveMapper;
import com.wskj.workbench.service.ITbUserReceiveService;
import com.wskj.workbench.vo.app.AppTbUserReceiveVo;
import com.wskj.workbench.vo.web.TbUserReceiveVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户收货地址信息Service业务层处理
 *
 * @author wsdz
 * @date 2022-09-26
 */
@Service
public class TbUserReceiveServiceImpl extends ServicePlusImpl<TbUserReceiveMapper, TbUserReceive> implements ITbUserReceiveService {

    @Override
    public TbUserReceiveVo queryById(Long receiveId){
        return getVoById(receiveId, TbUserReceiveVo.class);
    }

    @Override
    public TableDataInfo<TbUserReceiveVo> queryPageList(TbUserReceiveQueryBo bo) {
        PagePlus<TbUserReceive, TbUserReceiveVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), TbUserReceiveVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TbUserReceiveVo> queryList(TbUserReceiveQueryBo bo) {
        return listVo(buildQueryWrapper(bo), TbUserReceiveVo.class);
    }

    private LambdaQueryWrapper<TbUserReceive> buildQueryWrapper(TbUserReceiveQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbUserReceive> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, TbUserReceive::getUserId, bo.getUserId());
        lqw.like(StrUtil.isNotBlank(bo.getReceiveName()), TbUserReceive::getReceiveName, bo.getReceiveName());
        lqw.eq(StrUtil.isNotBlank(bo.getReceivePhone()), TbUserReceive::getReceivePhone, bo.getReceivePhone());
        lqw.eq(StrUtil.isNotBlank(bo.getAddress()), TbUserReceive::getAddress, bo.getAddress());
        lqw.eq(bo.getIfDefault() != null, TbUserReceive::getIfDefault, bo.getIfDefault());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(TbUserReceiveAddBo bo) {
        TbUserReceive add = BeanUtil.toBean(bo, TbUserReceive.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(TbUserReceiveEditBo bo) {
        TbUserReceive update = BeanUtil.toBean(bo, TbUserReceive.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TbUserReceive entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public String importTzUserReceive(List<TbUserReceiveVo> tzUserReceiveList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(tzUserReceiveList), "导入数据不能为空");
        int successNum = 0;
        for (TbUserReceiveVo tzUserReceive : tzUserReceiveList) {
            TbUserReceive add = BeanUtil.toBean(tzUserReceive, TbUserReceive.class);
            save(add);
            successNum++;
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", tzUserReceiveList.size(), successNum);
        if (successNum != tzUserReceiveList.size()) {
            msg = msg + String.format("失败 %d 条！", tzUserReceiveList.size() - successNum);
        }
        return msg;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addReceive(AppTbUserReceiveAddBo addBo) {
        // 用户ID
        Long userId = SecurityUtils.getUserId();
        TbUserReceive tzUserReceive = BeanUtil.toBean(addBo, TbUserReceive.class);
        // 客户ID
        tzUserReceive.setUserId(userId);
        if (IfDefaultEnum.YES.getValue().equals(addBo.getIfDefault())) {
            this.updateNotDefault(userId);
        }
        return baseMapper.insert(tzUserReceive);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editReceive(AppTbUserReceiveEditBo editBo) {
        // 用户ID
        Long userId = SecurityUtils.getUserId();
        TbUserReceive tzUserReceive = BeanUtil.toBean(editBo, TbUserReceive.class);
        if (IfDefaultEnum.YES.getValue().equals(editBo.getIfDefault())) {
            this.updateNotDefault(userId);
        }

        return baseMapper.updateById(tzUserReceive);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editDefault(AppTbUserReceiveEditBo editBo) {
        // 用户ID
        Long userId = SecurityUtils.getUserId();
        this.updateNotDefault(userId);
        LambdaUpdateWrapper<TbUserReceive> tbUserReceiveLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        tbUserReceiveLambdaUpdateWrapper.eq(TbUserReceive::getReceiveId,editBo.getReceiveId());
        tbUserReceiveLambdaUpdateWrapper.set(TbUserReceive::getIfDefault,IfDefaultEnum.YES.getValue());
        tbUserReceiveLambdaUpdateWrapper.set(TbUserReceive::getUpdateTime,new Date());
        return baseMapper.update(null,tbUserReceiveLambdaUpdateWrapper);
    }

    @Override
    public TableDataInfo<AppTbUserReceiveVo> pageList(AppTbUserReceiveQueryBo queryBo) {
        // 用户ID
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<TbUserReceive> lqw = Wrappers.lambdaQuery();
        lqw.eq(TbUserReceive::getUserId, userId);
        PagePlus<TbUserReceive, AppTbUserReceiveVo> result = pageVo(PageUtils.buildPagePlus(),lqw, AppTbUserReceiveVo.class);
        return PageUtils.buildDataInfo(result);
    }

    /**
     * 把其他都更新成不是默认地址
     * @param userId
     */
    private void updateNotDefault(Long userId) {
        TbUserReceive update = new TbUserReceive();
        update.setIfDefault(IfDefaultEnum.NO.getValue());
        baseMapper.update(update, Wrappers.<TbUserReceive>lambdaUpdate().eq(TbUserReceive::getIfDefault, IfDefaultEnum.YES.getValue()).eq(TbUserReceive::getUserId, userId));
    }
}
